package com.korovyansk.mapsproto.api;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.korovyansk.mapsproto.application.MapsProtoApplication.PerformanceTimer;
import com.korovyansk.mapsproto.beans.Position;
import com.korovyansk.mapsproto.beans.Tile;

/**
 * Utility class for download tiles from server
 * @author korovyansk
 */
public class TileDownloader {
	
	/**
	 * Downloads from korovyansk.appspot.com specified tile
	 * @param x - x coordinate of tile
	 * @param y - y coordinate of tile
	 * @return - target tile
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public Tile load(final Position position) throws MalformedURLException, IOException{
		final PerformanceTimer timer = new PerformanceTimer("load tile from server", true);
		final Bitmap bitmap = fetchBitmap(String.format(URL_TEMPLATE, position.x, position.y));
		//final Bitmap bitmap = fetchBitmap("http://img-fotki.yandex.ru/get/5905/kliopa-08.6f/0_611d1_ff048180_XL");
		timer.check();
		return new Tile(bitmap, position);
	}
	
	protected Bitmap fetchBitmap(final String url) throws MalformedURLException, IOException{
		return BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
	}
	
	private static final String URL_TEMPLATE = "http://korovyansk.appspot.com/tiles?x=%d&y=%d";
}
